package com.lushu.helpers {
import com.lushu.data.ZoneInfo;
import com.lushu.info.ApplicationData;

import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.URLLoader;
import flash.net.URLRequest;

public class ZoneReader extends EventDispatcher {
    private static var ZONE_LIST:Vector.<ZoneInfo>

    private var toLoad_:int = 0;

    public function ZoneReader() {
        var XML_URL:String = ApplicationData.BASE_LOCATION + "/" + ApplicationData.ZONE_DIRECTORY + "/discovery.php";
        var myXMLURL:URLRequest = new URLRequest(XML_URL);
        var myLoader:URLLoader = new URLLoader(myXMLURL);
        myLoader.addEventListener("complete", dirListed, false, 0, true);
    }

    private function dirListed(event:Event):void {
        var zoneString:String = event.target.data;
        ZONE_LIST = new Vector.<ZoneInfo>();

        if (zoneString != "") {
            var zoneList:Array = zoneString.split(":");
            var zoneName:String;
            var currentZone:ZoneInfo;
            toLoad_ = zoneList.length;

            for (var i:int = 0; i < zoneList.length; i++) {
                zoneName = zoneList[i];

                currentZone = new ZoneInfo(zoneList[i]);
                currentZone.addEventListener("zoneLoaded", zoneLoaded, false, 0, true);

                ZONE_LIST.push(currentZone);
            }
        }
        else {
            dispatchEvent(new Event("allZonesLoaded"));
        }
    }

    private function zoneLoaded(e:Event):void {
        toLoad_--;
        if (toLoad_ == 0) {
            dispatchEvent(new Event("allZonesLoaded"));
        }
    }

    public static function getZones():Vector.<ZoneInfo> {
        return ZONE_LIST;
    }
}
}